package net.maku.custom.biza.service.customs.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import net.maku.custom.biza.controller.customers.query.CustomerInfoQuery;
import net.maku.custom.biza.controller.customers.query.CustomerSelectResponseVO;
import net.maku.custom.biza.controller.customers.query.CustomerShipmentsQuery;
import net.maku.custom.biza.controller.customers.vo.CustomerHResponseVO;
import net.maku.custom.biza.controller.customers.vo.CustomerHtmlResponseVO;
import net.maku.custom.biza.controller.customers.vo.CustomerInfoVO;
import net.maku.custom.biza.controller.customers.vo.CustomerShipmentsVo;
import net.maku.custom.biza.controller.followup.vo.FollowUpDetailsVO;
import net.maku.custom.biza.mapper.customers.CustomerInfoConvert;
import net.maku.custom.biza.mapper.customers.CustomerInfoDao;
import net.maku.custom.biza.controller.followup.query.FollowUpDetailsQuery;
import net.maku.custom.biza.mapper.followup.FollowUpDetailsDao;
import net.maku.custom.biza.pojo.customs.CustomerInfoEntity;
import net.maku.custom.biza.service.customs.CustomerInfoService;
import net.maku.framework.common.page.PageResult;
import net.maku.framework.common.service.impl.BaseServiceImpl;
import net.maku.framework.common.utils.DownloadUtils;
import net.maku.framework.common.utils.EasyExcelUtils;
import net.maku.framework.common.utils.Result;
import net.maku.framework.security.user.SecurityUser;
import net.maku.framework.security.user.UserDetail;
import net.maku.system.dao.SysUserDao;
import net.maku.system.entity.SysRoleEntity;
import net.maku.system.entity.SysUserEntity;
import net.maku.system.enums.SuperAdminEnum;
import net.maku.system.service.SysUserRoleService;
import net.maku.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 客户信息
 *
 * @author NULL
 * @since 1.0.0 2022-07-11
 */
@Service
@AllArgsConstructor
public class CustomerInfoServiceImpl extends BaseServiceImpl<CustomerInfoDao, CustomerInfoEntity> implements CustomerInfoService {
    @Autowired
    private FollowUpDetailsDao followUpDetailsDao;
    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserDao sysUserDao;
    @Override
    public PageResult<CustomerInfoVO> page(CustomerInfoQuery query) {
        UserDetail user = SecurityUser.getUser();
        List<SysRoleEntity> roleList = sysUserRoleService.getRoleList(user.getId());
        SysRoleEntity csManage = roleList.stream().filter(o -> o.getName().equalsIgnoreCase("CS_MANAGE")).findFirst().orElse(null);
        if (user.getSuperAdmin() != 1 && csManage == null){
            query.setCsId(user.getId());
        }
        IPage<CustomerInfoEntity> iPage = getPage(query);
        List<CustomerInfoVO> customerInfoVOS = baseMapper.selectRelList(iPage,query);

        return new PageResult<>(customerInfoVOS, iPage.getTotal());
    }

    @Override
    public PageResult<CustomerInfoVO> selectCustomerList(CustomerInfoQuery query) {
        IPage<CustomerInfoEntity> iPage = getPage(query);
        List<CustomerInfoVO> customerInfoVOS = baseMapper.selectRelList(iPage,query);

        return new PageResult<>(customerInfoVOS, iPage.getTotal());
    }

    @Override
    public CustomerInfoVO selectRelById(Long id) {
        CustomerInfoVO customerInfoVO = baseMapper.selectRelById(id);
        FollowUpDetailsQuery followUpDetailsQuery = new FollowUpDetailsQuery();
        followUpDetailsQuery.setCustomerId(id);
        List<FollowUpDetailsVO> followUpDetailsVOList = followUpDetailsDao.selectRelList(followUpDetailsQuery);
        customerInfoVO.setFollowUpDetailsVOList(followUpDetailsVOList);
        return customerInfoVO;
    }

    private QueryWrapper<CustomerInfoEntity> getWrapper(CustomerInfoQuery query){
        QueryWrapper<CustomerInfoEntity> wrapper = new QueryWrapper<>();

        return wrapper;
    }

    @Override
    public Result save(CustomerInfoVO vo) {
        LambdaQueryWrapper<CustomerInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerInfoEntity::getMobile,vo.getMobile());
        List<CustomerInfoEntity> list = this.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)){
            return Result.error("客户手机号不允许重复！");
        }
        CustomerInfoEntity entity = CustomerInfoConvert.INSTANCE.convert(vo);
        entity.setCreator(SecurityUser.getUserId());
        entity.setCreateTime(new Date());
        baseMapper.insert(entity);
        return Result.ok();
    }

    @Override
    public void update(CustomerInfoVO vo) {
        CustomerInfoEntity entity = CustomerInfoConvert.INSTANCE.convert(vo);
        entity.setUpdater(SecurityUser.getUserId());
        entity.setUpdateTime(new Date());
        updateById(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> idList) {
        removeByIds(idList);
    }

    @Override
    public void downloadShipments(HttpServletResponse response, CustomerShipmentsQuery query) {
        List<CustomerShipmentsVo> customerShipmentsVos = baseMapper.countCustomerShipments(query);
        String templateFileName = "template/shipments.xlsx";
        byte[] bytes = EasyExcelUtils.wrapDownloadExcel(templateFileName, ExcelTypeEnum.XLSX, null, customerShipmentsVos, null);
        DownloadUtils.wrapDownloadFile(new ByteArrayInputStream(bytes), "shipments.xlsx", response);
    }

    /**
     * 下拉框
     * @return
     */
    @Override
    public Result<CustomerHResponseVO> getData(Long id) {
        CustomerHResponseVO customerHResponseVO = new CustomerHResponseVO();
        if(id == null){
            UserDetail userDetail = SecurityUser.getUser();
            Long userId = userDetail.getId();
            String name = userDetail.getRealName();
            Integer superAdmin = userDetail.getSuperAdmin();
            customerHResponseVO.setOperateId(userId);
            customerHResponseVO.setOperateName(name);
            if (SuperAdminEnum.YES.getValue().equals(superAdmin)){
                userId = null;
            }
            customerHResponseVO.setList(baseMapper.selectHtml(userId));
            return Result.ok(customerHResponseVO);
        }
        SysUserEntity sysUserEntity = sysUserDao.getById(id);
        customerHResponseVO.setOperateId(sysUserEntity.getId());
        customerHResponseVO.setOperateName(sysUserEntity.getRealName());
        customerHResponseVO.setList(baseMapper.selectHtml(id));
        return Result.ok(customerHResponseVO);
    }

    @Override
    public Result<List<CustomerSelectResponseVO>> getSelectData() {
        Long userId = SecurityUser.getUserId();
        List<CustomerInfoEntity> list = baseMapper.selectByCreator(userId);
        List<CustomerSelectResponseVO> list1 = Convert.toList(CustomerSelectResponseVO.class,list);
        return Result.ok(list1);
    }

}